package AdvancedEncryptionStandard;

import org.apache.commons.codec.binary.Hex;

public class AesTest {

    private static final AES aes = new AES();

    public static void main(String[] args) throws Exception {
        AesTest aesTest = new AesTest();
//        aesTest.primaryTest();
        aesTest.middleTest();
        aesTest.primaryTest();
    }


    //使用书上的中间数据来进行代码调试
    private void middleTest() throws Exception {
        byte[] textBytes = Hex.decodeHex("0123456789abcdeffedcba9876543210");
        ByteStream textStream = new ByteStream(textBytes, 16);


        byte[] keyBytes = Hex.decodeHex("0f1571c947d9e8590cb7add6af7f6798");
        ByteStream keyStream = new ByteStream(keyBytes, 16);

        ByteStream[] byteStreams = aes.generateKey(keyStream, 10);
        for (int i = 0; i < 11; i++) {
            if (!byteStreams[i].equals(MiddleData.roundkeys[i])) {
                System.out.printf("第 %d 不轮正确 %n", i);
                System.out.println(byteStreams[i].toHexString());
                System.out.println(MiddleData.roundkeys[i].toHexString());
            }
        }

        ByteStream encryptData = aes.encrypt(textStream, aes.generateKey(keyStream, 10), 10);
        // System.out.println(encryptData.toHexString());
        // System.out.println("ff0b844a0853bf7c6934ab4364148fb9");

        ByteStream decryptData = aes.decrypt(encryptData, aes.generateKey(keyStream, 10), 10);
        // System.out.println(decryptData.toHexString());
    }

    private void primaryTest() throws Exception {
        AesTestData[] testData = new AesTestData[]{
                // 以下两个是正常密钥的测试数据
                new AesTestData("0f1571c947d9e8590cb7add6af7f6798", "0123456789abcdeffedcba9876543210",
                        "ff0b844a0853bf7c6934ab4364148fb9"),
                new AesTestData("3475bd76fa040b73f521ffcd9de93f24", "1b5e8b0f1bc78d238064826704830cdb",
                        "f3855216ddf401d4d42c8002e686c6e7"),
                new AesTestData("2b24424b9fed596659842a4d0b007c61", "41b267bc5905f0a3cd691b3ddaee149d",
                        "fba4ec67020f1573ed28b47d7286d298")
        };

        boolean flag = true;
        for (int i = 0; i < 3; i++) {
            ByteStream encryptRes = aes.encrypt(testData[i].getPlaintext(), testData[i].getKey(), 10);
            if (!testData[i].getCiphertext().equals(encryptRes)) {
                System.out.println(testData[i].getCiphertext().toHexString());
                System.out.println(encryptRes.toHexString());
                flag = false;
            }

            ByteStream decryptRes = aes.decrypt(encryptRes, testData[i].getKey(), 10);
            if (!decryptRes.equals(testData[i].getPlaintext())) {
                flag = false;
            }
        }

        if (flag) {
            System.out.println("DES.primaryTest：DES加解密测试通过");
        } else {
            System.out.println("DES.primaryTest：DES加解密测试不通过");
        }
    }

}
